#include "parse.h"

static int
parse_uint32_for_lbase(char **ptr, uint32_t *num, int base)
{
	 char *str = *ptr;
	 uint32_t result = 0;
	 
	 while (*str != 0)
	 {
		  if ('0' > *str || '0' + base <= *str)
		  {
			   *ptr = str;
			   return -1;
		  }
		  result = result * base + (*str - '0');

		  ++str;
	 }

	 *num = result;
	 *ptr = str;
	 return 0;
}

static int
parse_uint32_for_hbase(char **ptr, uint32_t *num, int base)
{
	 char *str = *ptr;
	 uint32_t result = 0;
	 char c;
	 
	 while (*str != 0)
	 {		  
		  c = *str;
		  if ('0' > c || '9' < c)
		  {
			   if (c >= 'a') c = c - 'a' + 'A';
			   if ('A' > c || 'A' + base - 10 <= c)
			   {
					*ptr = str;
					return -1;
			   }
			   else result = result * base + 10 + (c - 'A');
		  }
		  else result = result * base + (c - '0');

		  ++str;
	 }

	 *num = result;
	 *ptr = str;
	 
	 return 0;
}

int
parse_uint32(char **ptr, uint32_t *num)
{
	 char *str = *ptr;
	 int len = strlen(str), result;
	 
	 if (len > 1 && str[0] == '0')
	 {
		  ++str;
		  if (*str == 'x')
		  {
			   ++str;
			   result = parse_uint32_for_hbase(&str, num, 16);
		  }
		  else if ('0' <= *str && *str <= '7')
		  {
			   result = parse_uint32_for_lbase(&str, num, 8);
		  }
		  else result = -1;
	 }
	 else result = parse_uint32_for_lbase(&str, num, 10);

	 *ptr = str;
	 return result;
}
